package com.hos.operation.api;


import com.hos.net.req.BaseReq;
import com.hos.net.res.MsgHint;
import com.hos.utile.DLog;
import com.hos.utile.DateUtile;
import com.hos.utile.JsonUtile;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;

@Controller
public class ApiBase {
    private JdbcTemplate jdbcTemplate;

    protected JdbcTemplate getJdbcTemplate() {
        if (jdbcTemplate == null) {
            //ClassPathXmlApplicationContext[只能读放在web-info/classes目录下的配置文件]
            ApplicationContext ctx = new ClassPathXmlApplicationContext("spring-mvc.xml");
            jdbcTemplate = (JdbcTemplate) ctx.getBean("jdbcTemplate");
            DLog.e("getJdbcTemplate:重新获取");
        }
        return jdbcTemplate;
    }


    //检验数据 false（校验失败）
    protected BaseReq isVerifyDataJson(HttpServletRequest request, String json, String role) {
        String time = DateUtile.getDateFormat(new Date(), DateUtile.DATA_FORMAT_YMD_HMS);
        DLog.e(time +" "+ role + " 请求:" + json, true);
        BaseReq req = (BaseReq) JsonUtile.json2Obj(json, BaseReq.class);
        if (req == null) {
            req = new BaseReq();
            req.errorMsg = new MsgHint("请求格式错误").toJson();
            return req;
        }
        String service = req.service;
        if (service == null || service.equals("")) {
            req.errorMsg = new MsgHint("请求类型不能为空").toJson();
            return req;
        }
        DLog.e(time +" "+ role + " 请求:" + service, true);
        //签名
        String sign = request.getHeader("sign");
        if (sign == null || sign.equals("")) {
            req.errorMsg = new MsgHint("签名不能为空").toJson();
            return req;
        }
        if ("push".equals(sign)) {
            req.isVerify = true;
            return req;
        }
        String s = JsonUtile.obj2Json(req);
        if (!sign.equals(s)) {
            req.errorMsg = new MsgHint("签名验证失败").toJson();
            return req;
        }
        req.isVerify = true;
        return req;
    }

}
